package com.xps.and.yuntong.Ui;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.bumptech.glide.Glide;
import com.xps.and.yuntong.Constants;
import com.xps.and.yuntong.R;
import com.xps.and.yuntong.Utils.AppCommond;
import com.xps.and.yuntong.Utils.BitmapUtil;
import com.xps.and.yuntong.Utils.CommonUtils;
import com.xps.and.yuntong.Utils.DensityUtil;
import com.xps.and.yuntong.Utils.FileUtil;
import com.xps.and.yuntong.Utils.RegularValidation;
import com.xps.and.yuntong.aly.OssService;
import com.xps.and.yuntong.aly.STSGetter;
import com.xps.and.yuntong.aly.UIDisplayer;
import com.xps.and.yuntong.base.BaseActivity;
import com.jude.utils.JUtils;
import com.zhy.base.fileprovider.FileProvider7;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

//import io.reactivex.Flowable;

/**
 * Created by administrator on 2017-12-09.
 */

public class RegistTwoCeshiActivity extends BaseActivity implements View.OnClickListener {


    private static final String bucket = "";
    private static final int RESULT_LOAD_IMAGE = 1;
    private ImageView iv_fanhui, iv_right, iv_shangchuan_photo, portrait_ImageView;
    private TextView tv_middle, tv_photo;
    private RelativeLayout rl_photo;
    private EditText et_real_xingming, et_real_shenfen;
    private LinearLayout ll_regist_next2;

    private String picturePath = "";
    private String pictureName;
    String filename = "";
    private String xjxc = "1";
    private String User_Phone = "";
    private OssService ossService;
    private UIDisplayer displayer;

    //图片标记
    int successPicCount = 0;//已经成功的个数
    int actualPicCount = 0;//应该成功的个数
    static final int REQUEST_CODE_CAPTURE_CROP_PHOTO = 1;

    @Override
    protected void init(Bundle inBundle) {
        initView();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    private void initView() {

        iv_fanhui = (ImageView) findViewById(R.id.iv_fanhui);
        iv_right = (ImageView) findViewById(R.id.iv_right);
        iv_right.setVisibility(View.GONE);
        iv_shangchuan_photo = (ImageView) findViewById(R.id.iv_shangchuan_photo);
        portrait_ImageView = (ImageView) findViewById(R.id.portrait_ImageView);

        tv_middle = (TextView) findViewById(R.id.tv_middle);
        tv_middle.setText(R.string.ide_info);
        tv_photo = (TextView) findViewById(R.id.tv_photo);
        rl_photo = (RelativeLayout) findViewById(R.id.rl_photo);
        et_real_xingming = (EditText) findViewById(R.id.et_real_xingming);
        et_real_shenfen = (EditText) findViewById(R.id.et_real_shenfen);

        ll_regist_next2 = (LinearLayout) findViewById(R.id.ll_regist_next2);
        ll_regist_next2.setEnabled(false);

        iv_fanhui.setOnClickListener(this);
        iv_shangchuan_photo.setOnClickListener(this);
        rl_photo.setOnClickListener(this);
        ll_regist_next2.setOnClickListener(this);


        User_Phone = JUtils.getSharedPreference().getString("mobile_phone", "");
    }

    public OssService initOSS(String endpoint, UIDisplayer displayer) {
        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        if (Constants.stsServer.equals("")) {
            credentialProvider = new STSGetter();
        } else {
            credentialProvider = new STSGetter(Constants.stsServer);
        }
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(this, endpoint, credentialProvider, conf);
        return new OssService(oss, Constants.bucket, displayer);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        displayer = null;
        ossService = null;
        unRegEventBus();
    }

    @Override
    public void photoUploadSuccess() {
        successPicCount++;
        Log.e("111", "已经成功的个数" + successPicCount + "应该成功的个数" + actualPicCount + "photoUploadSuccess" + "twoActivity");
        tv_photo.setText("图片上传成功");
        ll_regist_next2.setEnabled(true);
        ll_regist_next2.setBackground(getResources().getDrawable(R.drawable.bg_dialog_lan));
//        dissmisDialog();

    }

    @Override
    public void photoUploadFail() {
        tv_photo.setText("图片上传失败,请重新上传");
        ll_regist_next2.setEnabled(false);
        ll_regist_next2.setBackground(getResources().getDrawable(R.drawable.bg_dialog_hui));
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_regist_two;
    }

    @Override
    protected void setData() {
        displayer = new UIDisplayer(this);
        ossService = initOSS(Constants.endpoint, displayer);
//        ossService.setCallbackAddress(Constants.callbackAddress);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_fanhui:

                finish();
                break;
            case R.id.rl_photo:

                selectDialog();
//                takePhotoNoCompress();
                break;

            case R.id.ll_regist_next2:
                if (!ableGoNext()) return;
                if (successPicCount == 0) {
                    startUpload();
                } else if (successPicCount >= 0 && successPicCount == actualPicCount) {

                    SharedPreferences sp = JUtils.getSharedPreference();
                    SharedPreferences.Editor spEd = sp.edit();
                    spEd.putString("name", et_real_xingming.getText().toString().trim());
                    spEd.putString("idcard_id", et_real_shenfen.getText().toString().trim());
                    spEd.commit();
                    //此处需要验证身份证号和姓名是否正确且一致
                    Intent intent = new Intent(RegistTwoCeshiActivity.this, RegistThreeActivity.class);
                    startActivity(intent);
                }

//                showDialogNoCancel();
//
//                if (successPicCount == 1) {
//                    verificationCode();
//                } else {
//                    startUpload();
//                }


                break;


        }
    }

    boolean ableGoNext() {
        if (picturePath.equals("")) {
            JUtils.Toast("请上传清晰正面照片");
            return false;
        } else if (TextUtils.isEmpty(et_real_xingming.getText().toString())) {
            JUtils.Toast("请输入姓名");
            return false;
        } else if (!RegularValidation.isLegalName(et_real_xingming.getText().toString())) {
            JUtils.Toast("请输入真实姓名");
            return false;
        } else if (et_real_xingming.getText().toString().length()<2||et_real_xingming.getText().toString().length()>6) {
            JUtils.Toast("请输入真实姓名");
            return false;
        } else if (TextUtils.isEmpty(et_real_shenfen.getText().toString())) {
            JUtils.Toast("请输入身份证号");
            return false;
        } else if (!RegularValidation.isLegalId(et_real_shenfen.getText().toString())) {
            JUtils.Toast("请输入正确的身份证号");
            return false;
        }
        return true;
    }


    void selectDialog() {
        final Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        TextView XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xjxc = "1";
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CODE_CAPTURE_CROP_PHOTO);
                bottomDialog.dismiss();
            }
        });
        TextView XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xjxc = "2";
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    picturePath = "head.jpg";
//                    pictureName = "REQUEST_DRIVER_HEAD";
                    File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                    picturePath = file.getAbsolutePath();
                    // 仅需改变这一行
                    Uri fileUri = FileProvider7.getUriForFile(RegistTwoCeshiActivity.this, file);
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                    startActivityForResult(takePictureIntent, REQUEST_CODE_CAPTURE_CROP_PHOTO);

                }
                bottomDialog.dismiss();
            }
        });

        TextView cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
    }

    //    public void takePhotoNoCompress() {
//        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//            filename = "touxiang.jpg";
//            File file = new File(Environment.getExternalStorageDirectory(), filename);
//            picturePath = file.getAbsolutePath();
//            Uri fileUri = FileProvider7.getUriForFile(this, file);
//            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//            startActivityForResult(takePictureIntent, REQUEST_CODE_CAPTURE_CROP_PHOTO);
//        }
//    }
//
//    void processBitmap(Bitmap sourceBitmap) {
//        int rotateDegree = FileUtil.getBitmapDegree(picturePath);
//        if (rotateDegree != 0) {//如果图片的旋转角度大于0 把角度归零后 重新存储到sd卡 上传
//            rotateBitmap(sourceBitmap, rotateDegree);
//        } else {
//
//            Flowable.just(picturePath)
//                    .subscribeOn(io.reactivex.schedulers.Schedulers.io())
//                    //此处需修改
//                    .observeOn(io.reactivex.android.schedulers.AndroidSchedulers.mainThread())
//                    .observeOn(io.reactivex.schedulers.Schedulers.newThread())
//                    .doOnNext((s) -> CommonUtils.saveBitmapToSD(s, sourceBitmap));
//
//            portrait_ImageView.setImageBitmap(sourceBitmap);
//        }
//    }

    void processBitmap(Bitmap sourceBitmap) {
        int rotateDegree = FileUtil.getBitmapDegree(picturePath);
        if (rotateDegree != 0) {//如果图片的旋转角度大于0 把角度归零后 重新存储到sd卡 上传
            Observable.just(BitmapUtil.rotateBitmapByDegree(sourceBitmap, 360 - (-rotateDegree)))
                    .subscribeOn(Schedulers.io())
                    .doOnNext((b) -> {
                                picturePath = "head.jpg";
                                File file = new File(Environment.getExternalStorageDirectory(), picturePath);
                                picturePath = file.getAbsolutePath();
                                CommonUtils.saveBitmapToSD(file.getAbsolutePath(), b);
                                JUtils.Log("doOnNext");
                            }
                    )
                    .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Bitmap>() {
                @Override
                public void onStart() {
                    super.onStart();
//                    showDialogNoCancel();
                }

                @Override
                public void onCompleted() {
//                    dissmisDialog();
                    startUpload();
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                }

                @Override
                public void onNext(Bitmap bitmap) {
                    portrait_ImageView.setImageBitmap(sourceBitmap);
                }
            });
        } else {

            picturePath = "head.jpg";
            File file = new File(Environment.getExternalStorageDirectory(), picturePath);
            picturePath = file.getAbsolutePath();
            CommonUtils.saveBitmapToSD(file.getAbsolutePath(), sourceBitmap);

            startUpload();
            portrait_ImageView.setImageBitmap(sourceBitmap);
        }
    }

    //上传图片
    void startUpload() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String objectName = "headImg/" + formatter.format(curDate) + "/" + User_Phone + "/head.jpg";
        SharedPreferences sp = JUtils.getSharedPreference();
        SharedPreferences.Editor spEd = sp.edit();
        spEd.putString("head_img", objectName);
        spEd.commit();
        Log.e("111", objectName);
        ;
        ossService.asyncPutImage(objectName, picturePath, User_Phone);
//        showDialogNoCancel();
        actualPicCount++;
    }

    void doUploadOSS(String address) {
        actualPicCount++;
        Log.e("111", "已经成功的个数" + successPicCount + "应该成功的个数" + actualPicCount + "doUploadOSS");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String IDBackName = address + formatter.format(curDate) + "/" + User_Phone + "/head.jpg";
        SharedPreferences sp = JUtils.getSharedPreference();
        SharedPreferences.Editor spEd = sp.edit();
        spEd.putString("head_img", IDBackName);
        spEd.commit();
        Log.e("111", IDBackName);
        ossService.asyncPutImage(IDBackName, picturePath, User_Phone);
//        showDialogNoCancel();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CAPTURE_CROP_PHOTO) {
//            processBitmap(BitmapUtil.getSmallBitmap(picturePath, 480, 640));
////            startUpload();
//        }

        if (requestCode == REQUEST_CODE_CAPTURE_CROP_PHOTO) {
            if (xjxc.equals("1")) {
                if (data == null || resultCode != RESULT_OK) return;
                picturePath = CommonUtils.getRealFilePath(this, data.getData());
                switch (requestCode) {
                    case REQUEST_CODE_CAPTURE_CROP_PHOTO:
                        Glide.with(this).load(picturePath).into(portrait_ImageView);
                        Log.e("111", "已经成功的个数" + successPicCount + "应该成功的个数" + actualPicCount);
                        processBitmap(BitmapUtil.getSmallBitmap(picturePath, 400, 600));
//                        doUploadOSS("headImg/");
                        break;
                }
            } else if (xjxc.equals("2")) {
                if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CAPTURE_CROP_PHOTO) {
                    processBitmap(BitmapUtil.getSmallBitmap(picturePath, 400, 600));
//                    startUpload();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppCommond a) {
        if (!AppCommond.check(a)) return;
        for (String activityName : a.getAcNameList()) {
            if (activityName.contains(getClass().getSimpleName())) {
                unRegEventBus();
                finish();
                break;
            }
        }
    }

    void unRegEventBus() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }
}